<?php

include_once "baseChannel.php";
// 时间相差8小时
date_default_timezone_set("Asia/Shanghai");
class xiangda extends BaseChannel
{
    // 
    protected $appSecret;
    protected $url = '';
    public function __construct($options)
    {
        parent::__construct($options);
        $this->appSecret = $options['ApiKey'];
        $this->account = $options['account'];
        $this->url = $options['url'];
        $this->v = 'h1.1';
    }
    // 计算签名提单需要签名  emptyWithSign 为空是否参与签名
    public function getSign($data, $emptyWithSign = false)
    {
        foreach ($data as $key => &$val) {
            if (!$emptyWithSign) {
                if (empty($val)) {
                    unset($data[$key]);
                }
            }
            if (isset($data['sign'])) {
                unset($data['sign']);
            }
            // if ($key == 'account') {
            //     $val = $this->unicodeDecode($val);
            // }
        }
        ksort($data);
        $data['key'] = $this->appSecret;
        $str = http_build_query($data);

        $str = urldecode($str);
        $sign = md5($str);
        return $sign;
    }
    function unicodeDecode($unicode_str)
    {
        $json = '{"str":"' . $unicode_str . '"}';
        $arr = json_decode($json, true);
        if (empty($arr)) return '';
        return $arr['str'];
    }
    public function queryBalance($params = [])
    {
        $data = [
            "action" => "getBalance",
            "v" => $this->v,
        ];
        $signData = [
            "account" => $this->account
        ];
        $data['sign'] = $this->getSign($signData);
        $newData = array_merge($data, $signData);
        $url = $this->url . '?' . http_build_query($newData);
        $return_str = $this->httpRequest($url, 'GET');
        $return_data = json_decode($return_str, 1);
        if ($return_data['Code'] == 0) {
            return [
                'error' => 0,
                'msg' => $return_data['Message'] ?? '查询成功',
                'balance' => $return_data['Balance'] ?? 0, //余额
                'credit' =>  0, //授信 creditQuota
                'code' => 200,
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['Message'] ?? '查询失败',
            'code' => 500
        ];
    }
    public function queryOrder($params)
    {
        $data = [
            'action' => "queryReport",
            'v' => $this->v,
            'outTradeNo' => $params['push_order_sn'],
            "sendTime" => date('Y-m-d')
        ];
        $signData = [
            "account" => $this->account
        ];
        $data['sign'] = $this->getSign($signData);
        $newData = array_merge($data, $signData);
        $url = $this->url . "?" . http_build_query($newData);
        $return_str = $this->httpRequest($url, 'GET');
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' => '', //凭证
            'post_data' => $data, //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        //待充
        if ($return_data['Code'] == 0 && $return_data['Reports'][0]['Status'] == 7) {
            $ret['msg'] = $return_data['Reports'][0]['ReportCode'] ?? '待充值';
        }
        //处理中
        if ($return_data['Code'] == 0 && $return_data['Reports'][0]['Status'] == 2) {
            $ret['msg'] = $return_data['Reports'][0]['ReportCode'] ?? '充值中';
        }
        // 成功
        if ($return_data['Code'] == 0 && $return_data['Reports'][0]['Status'] == 4) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '查询充值完成:' . $return_data['Reports'][0]['ReportCode'];
        }
        // 失败
        if ($return_data['Code'] == 0 && $return_data['Reports'][0]['Status'] == 5) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '查询充值失败:' . $return_data['Reports'][0]['ReportCode'] ?? '';
        }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $data = [
            "action" => "charge",
            "v" => $this->v,
            "range" => 0,
            "backUrl" => $this->callback_url,
            "outTradeNo" => $params['push_order_sn'],
        ];
        $signData = [
            "account" => $this->account,
            "mobile" => $mobile,
            "package" => $code,
        ];
        $data['sign'] = $this->getSign($signData);
        $newData = array_merge($data, $signData);
        $return_str = $this->httpRequest($this->url, 'POST', $newData);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'url' => $this->url,
            'error' => -1,
            'msg' => '初始化',
            'channel_order' =>  '',
            'post_data' => json_encode($newData),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' =>   null,
            'channel_balance' =>  null,
        ];

        if ($return_data['Code'] == 0) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['Message'] ?? '下单成功';
        } else {
            if (isset($return_data['TaskID']) && $return_data['TaskID'] == 0) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['Message'] ?? '下单失败';
            }
        }
        return $ret;
    }
    public function callback($params)
    {
        $this->callback_params = $params;
        $this->channel_order_sn = "";
        $this->push_order_sn = $params['OutTradeNo'];
        //返回参数
        $res = $this->initCallBackParam();
        $signData = [
            "TaskID" => $params['TaskID'],
            "Mobile" => $params['Mobile'],
            "Status" => $params['Status'],
            "ReportTime" => $params['ReportTime'],
            "ReportCode" => $params['ReportCode'],
            "OutTradeNo" => $params['OutTradeNo'],

        ];
        //订单状态
        $order_status = $params['Status'];
        //凭证
        $pz =  '';
        // 验证签名
        $sign = $this->decrypt($signData);
        if ($sign !== $params['Sign']) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            $res['signature'] = $sign;
            return $res;
        }
        if ($order_status == 4) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = '充值完成';
            $res['resp_data'] = 'ok';
        }
        if ($order_status == 5) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] =  '充值失败';
            $res['resp_data'] = 'ok';
        }
        return $res;
    }
    //获取当前时间的毫秒
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    // 获取当前时间包括毫秒
    public function getCurDate($isSecond = false)
    {
        if ($isSecond) {
            return time();
        } else {
            $time = $this->msectime();
            $timestamp = time() . substr($time, -3);
            return $timestamp;
        }
    }
    public function decrypt($data, $emptyWithSign = false)
    {
        foreach ($data as $key => $val) {
            if (!$emptyWithSign) {
                if (empty($val)) {
                    unset($data[$key]);
                }
            }
            if (isset($data['sign'])) {
                unset($data['sign']);
            }
        }

        ksort($data);
        $str = http_build_query($data);
        $str = urldecode($str);
        $str .= $this->appSecret;

        $sign = md5($str);
        return $sign;
    }
}
